package com.coyote.common.base;

import com.coyote.common.enums.ErrorCodeEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;

@Data
@Schema(name = "Responses", description = "统一数据返回")
public class Responses<T> implements Serializable {

    private static final long serialVersionUID = 9176125179872407986L;

    @Schema(description = "响应码", example = "1001")
    private String code;

    @Schema(description = "响应数据")
    private T data;

    @Schema(description = "响应消息", example = "执行成功")
    private String msg;

    @Schema(description = "提示信息", example = "后台需要提示的信息，一般用于提示用户错误的信息")
    private String tip;

    @Schema(description = "响应时间", example = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime time = LocalDateTime.now();

    @Schema(description = "链路追踪ID")
    private String traceId;

    public Responses() {
        // 返回链路追踪ID
//        this.traceId = MDCTraceManager.getTraceId();
    }


    public static <T> Responses<T> ok(T data) {
        ErrorCodeEnum result = ErrorCodeEnum.SUCCESS;
        // 当传入的data为false时，表示执行失败
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            result = ErrorCodeEnum.FAILED;
        }
        Responses<T> responses = new Responses<>();
        responses.setData(data);
        responses.setCode(result.getCode());
        responses.setMsg(result.getMsg());
        responses.setTip(null);
        return responses;
    }


    public static <T> Responses<T> failed(T data, String errorMsg) {
        ErrorCodeEnum failed = ErrorCodeEnum.FAILED;
        Responses<T> responses = new Responses<>();
        responses.setData(data);
        responses.setCode(failed.getCode());
        responses.setMsg(failed.getMsg());
        responses.setTip(errorMsg);
        return responses;
    }
}
